package com.nb.system.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.free.common.utils.web.Servlets;
import com.nb.common.utils.Encryption;
import com.nb.common.utils.SearchFilter;
import com.nb.system.NewPager;
import com.nb.system.model.Department;
import com.nb.system.model.User;
import com.nb.system.service.DepartmentService;
import com.nb.system.service.RoleService;
import com.nb.system.service.UserService;

/**
 * 用户管理
 * @author mefly
 *
 */
@Controller
@RequestMapping(value="/system/user")
public class UserController {
	@Autowired
	private UserService service;
	@Autowired
	private RoleService roleService;
	@Autowired
	private DepartmentService departmentService;
	
	/*
	 * 用户列表
	 */
	@RequestMapping("/ajax_list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request,
			@RequestParam(value="page",defaultValue="1") int page ,
			@RequestParam(value="pagesize",defaultValue="10") int pagesize){
		
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		
		NewPager pager = new NewPager();
		pager.setPageNumber(page);
		pager.setPageSize(pagesize);
		pager.setFilters(filters);
		
		return service.queryPage(pager);
	}
	
	/*
	 * 录入
	 */
	@RequestMapping("/input")
	public String input(HttpServletRequest request,
			@RequestParam(value="id",defaultValue="0") int id ){
		User u =  service.fetch(id);
		request.setAttribute("ob", u);
		List<Department> l = departmentService.query(Cnd.where("id","=",u.getDeptid()));
		if(l.size()>0){
			//u.setDeptname(l.get(0).getDeptname());
		}
		return "jsp/system/input-user";	
	}

	/*
	 * 录入
	 */
	@RequestMapping("/inputRole")
	public String inputRole(HttpServletRequest request,
			@RequestParam(value="id",defaultValue="0") int id ){
		request.setAttribute("ob", service.fetchUserRoles(id));
		
		request.setAttribute("roles", roleService.query(null));
		return "jsp/system/input-user-role";	
	}
	/*
	 * 保存用户的角色
	 */
	@RequestMapping("/saveRole")
	@ResponseBody
	public String saveRole(HttpServletRequest request,
			@RequestParam(value="id",defaultValue="0") int id,
			@RequestParam(value="role") int[] roles ){
		//先删除后插入
		service.deleteUserRole(id);
		service.insertUserRole(roles,id);
		
		return "ok";	
	}
	/*
	 * 登录
	 */
	@RequestMapping("/login")
	public String login(@RequestParam(value="loginname",defaultValue="") String ln,
			@RequestParam (value="password",defaultValue="") String pw,
			HttpServletRequest request){
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(ln, Encryption.hashToMD5(pw));
		token.setRememberMe(true);
		
		try {
			currentUser.login(token);
		} catch (AuthenticationException e) {
			request.setAttribute("message", "登录失败：用户名或密码输入错误！");
			e.printStackTrace();
			throw new RuntimeException("登录失败：用户名或密码输入错误！");
		}
		if(currentUser.isAuthenticated()){

//			Condition c = Cnd.where("loginname","=",currentUser.getPrincipal().toString());
//		    List<User> users = service.query(c);
//		    currentUser.getSession().setAttribute("currentUser", users.get(0));
//		    currentUser.getSession().setAttribute("currentUserId", users.get(0).getId());
	    
			return "redirect:/index.jsp";
		}else{
			request.setAttribute("message", "登录失败：用户没有权限");
		}
		return "login";	
	}
	
	/**
	 * 退出登录
	 * 
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout() {
		Subject currentUser = SecurityUtils.getSubject();
		try {
			currentUser.logout();
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		return "login";
	}
	
	/*
	 * 保存
	 */
	@RequestMapping("/save")
	public String save(User user,
						HttpServletRequest request){
		if (user.getId()==null){
			service.insert(user);
		}else{
			service.update(user);
		}
		return "common/success";	
	}
	
	/*
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(HttpServletRequest request,
			@RequestParam(value="id",defaultValue="0") int id){
			service.delete(id);
		return "ok";	
	}
}
